//
//  LXLTabBar.swift
//  Weibo-YQY-test
//
//  Created by Lang on 10/9/15.
//  Copyright © 2015 Lang. All rights reserved.
//

import UIKit

class LXLTabBar: UITabBar {
    
    // 定义一个按钮点击的闭包
    var composeButtonClickBlock: (()->())?
    
    var composeButton: UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let composeButton = UIButton()
        // 添加点击事件
        composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置 button 的背景图
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button__highlighted"), forState: UIControlState.Highlighted)
        
        // 设置 button 的 image
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置大小
         composeButton.sizeToFit()
        
        addSubview(composeButton)
        
        self.composeButton = composeButton
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    // 按钮的点击事件
    @objc private func composeButtonClick(){
    
        //print("点击了加号按钮")
        
        printLog("按钮点击了")
        
        if let block = self.composeButtonClickBlock {
            block()
        }
        
    }
    
    
    
    
    // 设置按钮的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置加号按钮的位置
        self.composeButton?.center = CGPointMake(self.center.x, self.frame.size.height * 0.5)
        
        // 每一个按钮的宽度
        let childW = frame.size.width / 5
        
        // 定义一个脚标来记录当前 button 的位置
        var index = 0
        
        // 设置 UITabBarButton
        for childView in subviews {
            
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                // 设置按钮的宽
//                var frame = childView.frame
//                frame.size.width = childW
                childView.width = childW
                
                // 设置按钮的 x
//                frame.origin.x = CGFloat(index) * childW
//                childView.frame = frame
                childView.x = CGFloat(index) * childW
                
                index += (index == 1) ? 2 : 1
                
//                index++
//                
//                if index == 2 {
//                    index++
//                }
               
                
            }
            
       
        }
        
    }
    
}
